const fs = require('fs')
const path = require('path')
const { nanoid } = require('nanoid')


class UsersController {
	async getVerCode(req, res, next) {
		let myPath = path.join(__dirname, '../data/users.json');
		const usersList = JSON.parse(fs.readFileSync(myPath, 'utf8')).users;
		const { phone } = req.query
		const verCode = String(parseInt(Math.random() * 10 ** 6)).padStart(6, 0)
		const index = usersList.findIndex(user => user.phone === phone)
		if (index != -1) {
			usersList[index].verCode = verCode
		} else {
			usersList.push({
				id: nanoid(),
				phone,
				verCode
			})
		}
		fs.writeFileSync(myPath, JSON.stringify({ users: usersList }))
		res.json({
			code: 200,
			msg: '获取成功',
			data: { verCode }
		})
	}

	async login(req, res, next) {
		let myPath = path.join(__dirname, '../data/users.json');
		const usersList = JSON.parse(fs.readFileSync(myPath, 'utf8')).users;
		const { phone, verCode } = req.query
		let user = {}
		if (user = usersList.find(user => user.phone === phone && user.verCode === verCode)) {
			res.json({
				code: 200,
				msg: '登录成功',
				data: {
					user: {
						"id": user.id,
						"phone": user.phone,
						"password": user.password,
						"avatar": user.avatar,
						"gender": user.gender,
						"name": user.name,
						"birth": user.birth
					}
				}
			})
		} else {
			res.json({
				code: 403,
				msg: '登录失败'
			})
		}
	}


	async addUser(req, res, next) {
		let myPath = path.join(__dirname, '../data/users.json');
		const usersList = JSON.parse(fs.readFileSync(myPath, 'utf8')).users;
		const { phone, password } = req.body

		try {
			const newUser = {
				id: nanoid(),
				phone,
				password
			}
			usersList.push(newUser)
			fs.writeFileSync(myPath, JSON.stringify({ users: usersList }))
			res.json({
				code: 200,
				msg: '注册成功',
				data: newUser
			})
		}
		catch (e) {
			res.json({
				code: 403,
				msg: '注册失败'
			})
		}
	}
}

module.exports = new UsersController();